package tree;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 501.二叉搜索树中的众数
 * 既然是搜索树，它中序遍历就是有序的。
 * 双指针
 *
 * @author Api
 * @date 2023/10/27 0:04
 */
public class Code501_ModeInBinarySearchTree {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    // 暴力法(普通的二叉树求众数的操作步骤)
    public int[] findMode(TreeNode root) {
        Map<Integer, Integer> map = new HashMap<>();
        List<Integer> list = new ArrayList<>();
        if (root == null) {
            return list.stream().mapToInt(Integer::intValue).toArray();
        }
        // 获得频率 Map
        searchBST(root, map);
        List<Map.Entry<Integer, Integer>> mapList = map.entrySet().stream().sorted((c1, c2) -> c2.getValue().compareTo(c1.getValue())).collect(Collectors.toList());
        list.add(mapList.get(0).getKey());
        // 把频率最高的加入到list
        for (int i = 1; i < mapList.size(); i++) {
            if (mapList.get(i).getValue().equals(mapList.get(i - 1).getValue())) {
                list.add(mapList.get(i).getKey());
            } else {
                break;
            }
        }
        return list.stream().mapToInt(Integer::intValue).toArray();
    }

    void searchBST(TreeNode curr, Map<Integer, Integer> map) {
        if (curr == null) {
            return;
        }
        map.put(curr.val, map.getOrDefault(curr.val, 0) + 1);
        searchBST(curr.left, map);
        searchBST(curr.right, map);
    }

    // 中序遍历-不使用额外空间，利用二叉搜索树特性（中序遍历，有序）
    List<Integer> resList;
    int maxCount;
    int count;
    TreeNode pre;

    public int[] findMode1(TreeNode root) {
        resList = new ArrayList<>();
        maxCount = 0;
        count = 0;
        pre = null;
        traversal(root);
        int[] res = new int[resList.size()];
        for (int i = 0; i < resList.size(); i++) {
            res[i] = resList.get(i);
        }
        return res;
    }

    private void traversal(TreeNode root) {
        if (root == null) {
            return;
        }
        traversal(root.left);
        // 计数
        int rootValue = root.val;
        if (pre == null || rootValue != pre.val) {
            count = 1;
        } else {
            count++;
        }
        // 更新结果以及maxCount;
        if (count > maxCount) {
            resList.clear();
            resList.add(rootValue);
            maxCount = count;
        } else if (count == maxCount) {
            resList.add(rootValue);
        }
        pre = root;
        traversal(root.right);
    }

    // 迭代法
    public int[] findMode2(TreeNode root) {
        TreeNode pre = null;
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> result = new ArrayList<>();
        int maxCount = 0;
        int count = 0;
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            if (cur != null) {
                stack.push(cur);
                cur = cur.left;
            } else {
                cur = stack.pop();
                // 计数
                if (pre == null || cur.val != pre.val) {
                    count = 1;
                } else {
                    count++;
                }
                // 更新结果
                if (count > maxCount) {
                    maxCount = count;
                    result.clear();
                    result.add(cur.val);
                } else if (count == maxCount) {
                    result.add(cur.val);
                }
                pre = cur;
                cur = cur.right;
            }
        }
        return result.stream().mapToInt(Integer::intValue).toArray();
    }

    // 统一迭代法
    public int[] findMode3(TreeNode root) {
        int count = 0;
        int maxCount = 0;
        TreeNode pre = null;
        LinkedList<Integer> res = new LinkedList<>();
        Stack<TreeNode> stack = new Stack<>();

        if (root != null) {
            stack.add(root);
        }

        while (!stack.isEmpty()) {
            TreeNode curr = stack.peek();
            if (curr != null) {
                stack.pop();
                if (curr.right != null) {
                    stack.add(curr.right);
                }
                stack.add(curr);
                stack.add(null);
                if (curr.left != null) {
                    stack.add(curr.left);
                }
            } else {
                stack.pop();
                TreeNode temp = stack.pop();
                if (pre == null) {
                    count = 1;
                } else if (pre != null && pre.val == temp.val) {
                    count++;
                } else {
                    count = 1;
                }
                pre = temp;
                if (count == maxCount) {
                    res.add(temp.val);
                }
                if (count > maxCount) {
                    maxCount = count;
                    res.clear();
                    res.add(temp.val);
                }
            }
        }
        int[] result = new int[res.size()];
        int i = 0;
        for (int x : res) {
            result[i] = x;
            i++;
        }
        return result;
    }
}
